package com.b.repository;

import com.b.domain.DynamicComment;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface DynamicCommentRepository extends ElasticsearchRepository<DynamicComment, Integer> {

    List<DynamicComment> findByDynamicId(Integer dynamicId);

    List<DynamicComment> findByParentId(Integer parentId);

    // 新增计数更新方法
    default void refreshCommentCount(Integer commentId, Integer parentId, int increment) {
        // 1. 更新评论本身
        Optional<DynamicComment> commentOpt = findById(commentId);
        commentOpt.ifPresent(comment -> {
            if (parentId == null || parentId == 0) {
                // 顶级评论不需要更新回复数
            } else {
                // 更新父评论的回复数
                Optional<DynamicComment> parentOpt = findById(parentId);
                parentOpt.ifPresent(parent -> {
                    parent.setReplyCount(parent.getReplyCount() + increment);
                    save(parent);
                });
            }
            save(comment);
        });
    }
}
